<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:44
 */

namespace app\admin\service\business\controllers\Config;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\Config\Models\ConfigModel;
use app\service\alone\Path\PathService;

/**
 * Class ConfigService
 *
 * @property-read ConfigModel $model
 * @property-read PathService $path
 *
 * @package app\admin\service\business\controllers\Config
 */
class ConfigService extends BaseControllerService
{
    protected $rely = [
        'model' => ConfigModel::class,

        'path' => PathService::class,
    ];

    // 配置类型
    public $configType = [
        'config-base' => 0,
        'config-web' => 1
    ];

    /**
     * 查询列表
     *
     * @param array $where
     * @param int $limit
     * @return mixed
     * @throws \Exception
     */
    public function resList(array $where, int $limit)
    {
        $list = $this->model->getList($where['key'] ?? [], [], true, $limit);

        foreach ($list as $k => $v) {
            // 图片
            if ($v->type == 1) $list[$k]['value'] = $this->path->generateUrl($v->value)['url'];

            // 富文本
            if ($v->type == 2) $list[$k]['value'] = interceptStr(strip_tags(htmlspecialchars_decode($v->value)), 30);
        }

        return $list;
    }

    /**
     * 查询单条信息
     *
     * @param int $id
     * @return mixed
     * @throws \Exception
     */
    public function resFind(int $id)
    {
        $result = $this->model->getFind($id);

        // 图片
        if (1 == $result->value_type) $result->value = json_encode($this->path->generateUrl($result->value));

        // 富文本
        if (2 == $result->value_type) $result->value = $this->path->richTextEncryptionPath(htmlspecialchars_decode($result->value));

        return $result;
    }

    /**
     * 操作数据
     *
     * @param array $params
     * @param int $id
     * @return array
     */
    public function operating(array $params, int $id = 0): array
    {
        if ($params['value_type'] == 1) {
            // 图片
            if (false === $value = $this->path->fileHandler($params['value'])) return echoArr(301);
        } else if ($params['value_type'] == 2) {
            // 富文本
            $valueResult = $this->path->richTextPath($params['value']);
            if (200 != $valueResult['code']) return echoArr(302);

            $value = htmlspecialchars($valueResult['data']);
        } else {
            // 文本
            $value = $params['value'];
        }

        // 需操作的数据
        $data = [
            'value' => $value,
            'description' => $params['description'],
        ];

        try {
            // 执行数据更新
            if ($id) $this->model->edit($data, $id);
        } catch (\Exception $e) {
            return echoArr(800);
        }

        return echoArr(200);
    }
}
